package main

import (
	"encoding/binary"
	"fmt"
	"image"
	"image/jpeg"
	"io"
	"log"
	"os"
	"os/exec"
	"time"
)

func main() {
	cmd := exec.Command("adb", "shell", " screencap")
	out, _ := cmd.StdoutPipe()
	go func() {
		start := time.Now()
		buf, _ := io.ReadAll(out)
		width := int(binary.LittleEndian.Uint32(buf[:4]))
		height := int(binary.LittleEndian.Uint32(buf[4:8]))
		stride := binary.LittleEndian.Uint32(buf[8:12])
		format := binary.LittleEndian.Uint32(buf[12:16])
		size := width * height * 4
		offset := len(buf) - int(size)
		fmt.Printf("w:%v, h:%d,stride:%d, f:%d, size:%d, offset:%d, cost:%s\n", width, height, stride, format, size, offset, time.Since(start))
		if offset < 0 {
			return
		}
		img := ParseImage(buf, offset, width, height)
		file, err := os.Create("img.jpg")
		log.Println(err)
		err = jpeg.Encode(file, img, nil)
		log.Println(err, time.Since(start))
	}()
	cmd.Run()

	time.Sleep(5 * time.Second)
}

func ParseImage(buf []byte, offset int, width, height int) *image.RGBA {
	img := image.NewRGBA(image.Rect(0, 0, width, height))
	// img.Set(0, 0, color.RGBA{uint8(1), uint8(2), uint8(3), 255})
	img.Pix = buf[offset:]
	return img
}
